package com.demo.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import com.demo.service.ILock;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + ":";
    private String lockName;
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        //初始化
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));//执行脚本的位置
        UNLOCK_SCRIPT.setResultType(Long.class);//返回Long类型
    }
    public SimpleRedisLock(String lockName, StringRedisTemplate stringRedisTemplate) {
        this.lockName = lockName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁
     *
     * @param timeoutSec 锁的过期时间 到期自动释放
     * @return true代表成功 false代表获取锁失败
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程名称
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + lockName, threadId, timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);//拆箱
    }

    /**
     * 释放锁-lua脚本
     */
    @Override
    public void unlock() {
        //调用lua脚本 参数 1.脚本 2.key集合 3.线程标示
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + lockName),ID_PREFIX + Thread.currentThread().getId());
    }

    /**
     * 释放锁
     */
//    @Override
//    public void unlock() {
//        //获取线程名称
//        String threadId = ID_PREFIX + Thread.currentThread().getId();
//        //获取锁中的标示
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + lockName);
//        //判断是否是同一个线程标示
//        if (threadId.equals(id)) {
//            stringRedisTemplate.delete(KEY_PREFIX + lockName);
//        }
//    }
}
